<script src="__PUBLIC__/Static/libs/avalon/avalon.shim.min.js" charset="utf-8"></script>
<link rel="stylesheet" href="http://cdn.bootcss.com/font-awesome/4.2.0/css/font-awesome.min.css">
<style type="text/css">
    .modal-goods-name label {
        font-weight: normal;
        cursor: pointer;
    }
    .modal-body {
        max-height: 450px;
        overflow-y: auto;
    }
	.show{
		display: block;
	}
</style>

<div ms-controller="package-templete">
    <form action="" class="form-horizontal" role="form">

        <div class="form-group">
            <label for="" class="col-sm-2 control-label">套餐名称</label>
            <div class="col-sm-6">
                <input name="name" ms-duplex="goodsPackage.name" type="text" class="form-control" placeholder="请在此输入套餐名称" />
            </div>
        </div>

        <div class="form-group">
            <label class="col-sm-2 control-label">套餐横长图片<br />(建议宽高比 2:1)</label>
            <div class="col-sm-6">
                <input type="text" class="form-control margin-bottom" name="image" id="image" ms-duplex="goodsPackage.image" placeholder="请输入图片，或点击上传">
                <span class="btn btn-primary" id="image_upload">上传图片</span>
            </div>
        </div>

        <div class="form-group">
            <label class="col-sm-2 control-label">套餐竖长图片<br />(建议宽高比 1:2)</label>
            <div class="col-sm-6">
                <input type="text" class="form-control margin-bottom" name="image_vertical" id="image_vertical" ms-duplex="goodsPackage.image_vertical" placeholder="请输入图片，或点击上传">
                <span class="btn btn-primary" id="image_upload2">上传图片</span>
            </div>
        </div>

        <div class="form-group">
            <label class="col-sm-2 control-label">分享图片<br />(建议宽高比 1:1)</label>
            <div class="col-sm-6">
                <input type="text" class="form-control margin-bottom" name="image_share" id="image_share" ms-duplex="goodsPackage.image_share" placeholder="请输入图片，或点击上传">
                <span class="btn btn-primary" id="image_upload3">上传图片</span>
            </div>
        </div>
        
       <div class="form-group">
           <label for="" class="col-sm-2 control-label">折扣价</label>
           <div class="col-sm-6">
           	<div ms-repeat-val="goodsPackage['config']['base']['discount']">
           	<label>{{ $index+1 }}级代理:</label>
           	<input class="form-control" ms-duplex="val" type="number" />
           	</div>
           </div>
       </div>
          
       <div class="form-group">
           <label for="" class="col-sm-2 control-label">培养佣金</label>
           <div class="col-sm-6">
           	<input class="form-control" ms-duplex="goodsPackage['config']['base']['recommendBouns']" type="number" />
           </div>
       </div>
       
       <div class="form-group">
           <label for="" class="col-sm-2 control-label">培养分佣比例</label>
           <div class="col-sm-6">
           	<input class="form-control" ms-duplex="goodsPackage['config']['base']['recommendPercent']"/>
           </div>
       </div>

        <div class="form-group">
            <label for="" class="col-sm-2 control-label">套餐类型</label>
            <div class="col-sm-6">
                <select name="type" class="form-control" ms-duplex="goodsPackage.type">{$packageTypesOptions}</select>
	            <div class="form-group none" ms-class='show:goodsPackage.type==1' style="margin-top:15px;">
					<div class="form-group">
			            <label for="" class="col-sm-2 control-label">升级代理等级</label>
			            <div class="col-sm-6">
			                <select class="form-control" ms-duplex="goodsPackage['config'][1]['toLevel']">
			                	<option ms-repeat="agentLevelJson" ms-attr-value="$key">{{ $val }}</option>
							</select>
			            </div>
		            </div>
		        </div>
            </div>
        </div>
        
   		<div class="form-group">
          <label for="" class="col-sm-2 control-label">套餐价格</label>
          <div class="col-sm-6">
              <input name="price" class="form-control" ms-duplex="goodsPackage.price" ms-change="calculate" type="number" />
          </div>
        </div>

        <div class="form-group">
            <label for="" class="col-sm-2 control-label">折扣情况</label>
            <div class="col-sm-8">
                <div class="input-group">
                    <span class="input-group-addon">商品总量</span>
                    <input class="form-control" ms-attr-value="goodsCount" type="number" disabled="disabled" />
                    <span class="input-group-addon">商品总价</span>
                    <input class="form-control" ms-attr-value="goodsTotalPrice" type="number" disabled="disabled" />
                    <span class="input-group-addon">套餐折扣</span>
                    <input class="form-control" ms-attr-value="goodsPackageDiscount" type="number" disabled="disabled" />
                    <span class="input-group-addon">%</span>
                </div>
            </div>
        </div>

        <div class="form-group">
            <label for="" class="col-sm-2 control-label">套餐内产品</label>
            <div class="col-sm-10">
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th>序号</th>
                            <th>产品编号</th>
                            <th>产品名称</th>
                            <th>现价</th>
                            <th>数量</th>
                            <th>商品状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tr ms-repeat-goods="goodsPackage.goods">
                        <td>{{ $index+1 }}</td>
                        <td>{{ goods.id }}</td>
                        <td>{{ getGoodsInfo(goods.id, 'name') }}</td>
                        <td>{{ getGoodsInfo(goods.id, 'price') }}</td>
                        <td class="col-sm-1">
                            <input type="number" ms-duplex-number="goods.count" ms-change="calculate" class="form-control" step="1" />
                        </td>
                        <td>{{ getGoodsInfo(goods.id, 'status') }}</td>
                        <td><a href="javascript:void(0)" class="btn btn-danger btn-xs" ms-click="$remove"><i class="fa fa-times-circle"></i> 删除</a>
                        </td>
                    </tr>
                </table>
                <div style="padding-top:5px;">
                    <button class="btn btn-info" ms-click="addGoods"><i class="fa fa-plus-circle"></i> 添加商品</button>
                </div>
            </div>
        </div>
        
        <div class="form-group">
		    <label class="col-sm-2 control-label">运费</label>
		    <div class="col-sm-6">
		    	<div class="radio">
                    <label ms-repeat="shippingMethods" class="radio-inline"><input type="radio" ms-duplex-string="goodsPackage.shipping_method" ms-attr-value="{{ $val.value }}">{{ $val.name }}</label>
                </div>
			</div>
		</div>
		
		<div class="form-group none" ms-class='show:goodsPackage.shipping_method==0'>
            <label for="" class="col-sm-2 control-label">运费模板</label>
            <div class="col-sm-6">
                <select name="type" class="form-control" ms-duplex="goodsPackage.shipping_tpl_id">
                	<option ms-repeat="deliveryTplJson" ms-attr-value="$key">{{ $val }}</option>
				</select>
		        <div class="form-group none" ms-class='show:goodsPackage.shipping_tpl_id==0'>
				    <label class="col-sm-2 control-label">运费价格</label>
				    <div class="col-sm-6">
				    	<div class="radio">
				    		<foreach item="vo" name="deliveryMethods" key="key">
				    			<label style="padding-bottom:10px">{$vo['name']}：<input type="text" ms-duplex-string="goodsPackage.shipping_config['{$vo['value']}']" class="text text-short" maxlength="6" ms-attr-value=""> 元</label>
							</foreach>
		                </div>
					</div>
				</div>
            </div>
        </div>
		
        <div class="form-group">
            <label for="" class="col-sm-2 control-label">状态</label>
            <div class="col-sm-5">
                <div class="radio">
                    <label class="radio-inline">
                        <input type="radio" ms-duplex-string="goodsPackage.status" value="0">下架</label>
                    <label class="radio-inline">
                        <input type="radio" ms-duplex-string="goodsPackage.status" value="1">上架</label>
                </div>
            </div>
        </div>

        <div class="form-group">
            <div class="col-sm-2"></div>
            <div class="col-sm-10">
                <input type="hidden" name="id" ms-duplex="goodsPackage.id" />
                <button class="btn btn-default" onclick="javascript: history.back()">返回上页</button>
                <button class="btn btn-default" onclick="javascript: location.href=document.referrer">返回上页并刷新</button>
                <button type="submit" class="btn btn-primary" ms-click="submitForm">提交保存</button>
                <span id="submitMsg" class="label"></span>
            </div>
        </div>

    </form>

    <!--弹出窗口-->
    <div class="modal fade" id="addGoodsDialog" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title" id="myModalLabel">选择商品</h4>
                </div>
                <div class="modal-body">
                    <table class="table table-condensed table-striped table-hover">
                        <thead>
                            <tr>
                                <th></th>
                                <th>商品编号</th>
                                <th>商品价格</th>
                                <th>商品名称</th>
                                <tr>
                        </thead>
                        <tbody>
                            <tr ms-repeat="goodsList">
                                <td>
                                    <input type="checkbox" ms-duplex-number="goodsSelected" ms-attr-id="goods-{{ $val.id }}" ms-attr-value="$val.id" />
                                </td>
                                <td>{{ $val.id }}</td>
                                <td>{{ $val.price }}</td>
                                <td class="modal-goods-name">
                                    <label ms-attr-for="goods-{{ $val.id }}">{{ $val.name }}</label>
                                </td>
                                <tr>
                        </tbody>
                    </table>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-success" ms-click="addOk">确定</button>
                </div>
            </div>
        </div>
    </div>
</div>


<script type="text/javascript">
    // 套餐
    var goodsPackage = {$goodsPackage} || {};
    goodsPackage.goods = goodsPackage.goods || [];
    goodsPackage.status = goodsPackage.status || 0;
    goodsPackage.type = goodsPackage.type || "";
    goodsPackage.price = goodsPackage.price || 0;
    goodsPackage.pic = goodsPackage.pic || '';
    goodsPackage.shipping_config = goodsPackage.shipping_config || {};
    var deliveryTplJson = {$deliveryTplJson} || {},
        agentLevelJson = {$agentLevelJson} || {};

    //  goodsPackage.goods = [{id:102,count:2}];

    // 商品列表
    var goodsList = {$goodsList},
	    shippingMethods = {$shippingMethods},
	    deliveryMethods = {$deliveryMethods};

    var vm = avalon.define({
        $id: 'package-templete',
        goodsPackage: goodsPackage,
        goodsList: goodsList,
        goodsSelected: [],
        goodsCount: 0,
        goodsTotalPrice: 0,
        goodsPackageDiscount: 0,
        addGoods: function() {
            avalon.each(vm.goodsPackage.goods, function(k, v) {
                vm.goodsSelected.ensure(v.id-0);
            })
            $("#addGoodsDialog").modal();
        },
        addOk: function() {
            // 先把套餐中的商品备份出来
            var goodsBackup = {};
            avalon.each(vm.goodsPackage.goods.$model, function(k, v) {
                goodsBackup[v.id] = v;
            });
            // 清空套餐商品
            vm.goodsPackage.goods.clear();
            // 遍历选中的商品
            avalon.each(vm.goodsSelected, function(k, v) {
                // 检查选中的商品是否存在于套餐商品列表中
                var isExists = false;
                avalon.each(goodsBackup, function(key, val) {
                        if (v == key) {
                            isExists = true;
                            return false;
                        }
                });
                    // 如果存在，使用原有数据，不存在，新增加一条默认数据
                vm.goodsPackage.goods.push(isExists ? goodsBackup[v] : {
                    id: parseInt(v),
                    count: 1
                });
            })
            vm.calculate()
            $("#addGoodsDialog").modal("hide");
        },
        calculate: function() {
            var count = 0;
            var totalPrice = 0;
            avalon.each(vm.goodsPackage.goods, function(key, val) {
                count += val.count - 0;
                totalPrice += vm.goodsList[val.id].price * val.count;
            })
            var discount = Math.ceil(vm.goodsPackage.price / totalPrice * 10000) / 100;
            vm.goodsCount = count;
            vm.goodsTotalPrice = totalPrice;
            vm.goodsPackageDiscount = discount;
        },
        getGoodsInfo: function(id, attr) {
            if (attr == "status") {
                return ['下架', '上架'][vm.goodsList[id][attr]];
            }
            return vm.goodsList[id][attr];
        },
        submitForm: function() {
            $btnSubmit = $(this);
            var data = vm.goodsPackage.$model;
            $.ajax({
                type: "POST",
                url: "__CONTROLLER__/save",
                async: true,
                data: data,
                beforeSend: function() {
                    $btnSubmit.data("value", $btnSubmit.html()).html("<i class='fa fa-spin fa-spinner'></i> 正在提交中……").attr("disabled", true);
                },
                success: function(data) {
                    $("#submitMsg").html(data.msg).removeClass().addClass(['label label-success', 'label label-danger'][data.error]).show().delay(3000).fadeOut('slow');
                },
                error: function(error) {
                    $("#submitMsg").html(error).removeClass().addClass("label label-danger");
                },
                complete: function() {
                    $btnSubmit.html($btnSubmit.data("value"));
                    setTimeout(function(){
                        $btnSubmit.removeAttr("disabled")
                    },5000);
                }
            });
        }
    });
    vm.calculate()
    vm.goodsPackage.goods.$watch("length", function(length) {
        vm.calculate()
    })
</script>

<!-- uploadify -->
<link rel="stylesheet" href="__PUBLIC__/Style/Common/uploadify/uploadify.css">
<script src="__PUBLIC__/Style/Common/uploadify/jquery.uploadify.min.js?"></script>
<script type="text/javascript">
    $("#image_upload").uploadify({
        'multi': true,
        'buttonClass': 'margin-bottom',
        'fileSizeLimit': '200kb',
        'buttonText': '上传图片',
        'fileTypeDesc': 'Image Files',
        'fileTypeExts': '*.jpg; *.png',
        'swf': '__PUBLIC__/Style/Common/uploadify/uploadify.swf',
        'uploader': '__MODULE__/Upload/uploadOne',
        'onUploadStart': function() {},
        'onUploadSuccess': function(data, res) {
            var url = eval("(" + res + ")").extra.url;
            $("#image").val(url);
        }
    });

    $("#image_upload2").uploadify({
        'multi': true,
        'buttonClass': 'margin-bottom',
        'fileSizeLimit': '200kb',
        'buttonText': '上传图片',
        'fileTypeDesc': 'Image Files',
        'fileTypeExts': '*.jpg; *.png',
        'swf': '__PUBLIC__/Style/Common/uploadify/uploadify.swf',
        'uploader': '__MODULE__/Upload/uploadOne',
        'onUploadStart': function() {},
        'onUploadSuccess': function(data, res) {
            var url = eval("(" + res + ")").extra.url;
            $("#image_vertical").val(url);
        }
    });

    $("#image_upload3").uploadify({
        'multi': true,
        'buttonClass': 'margin-bottom',
        'fileSizeLimit': '200kb',
        'buttonText': '上传图片',
        'fileTypeDesc': 'Image Files',
        'fileTypeExts': '*.jpg; *.png',
        'swf': '__PUBLIC__/Style/Common/uploadify/uploadify.swf',
        'uploader': '__MODULE__/Upload/uploadOne',
        'onUploadStart': function() {},
        'onUploadSuccess': function(data, res) {
            var url = eval("(" + res + ")").extra.url;
            $("#image_share").val(url);
        }
    });
</script>